$j(document).ready(function () {
});



var mediaId = 0; //media计数器
var currentMiddleImageId;  //记录当前中图是哪个小图点击而打开的
var relatedContentCounter = 0; //关联文章计数器
var currentTypeId; //当前关联类型
	
function initVariables(){
	mediaId = 0;
	currentMiddleImageId = ""; 
	relatedContentCounter = 0;
	currentTypeId = "";
}



//显示操作按钮
function displayButtons(status){
	if(status == null){
		//case: 新增
		enableIconBtn("save");
		disableIconBtn("delete");
		disableIconBtn("updateExpired");
	}else{
		//case:编辑
		enableIconBtn("save");
		enableIconBtn("delete");
		enableIconBtn("updateExpired");
	}
	
}	 


//验证函数
function validateAction(){
	//先去掉旧的验证class
	if($('publishTime'))__handleVaErrMsg($('publishTime'),null);
	
	var flag = true;
	
	if($('publishTime')){
		$j('input[name="publishTimeRadio"]').each(function(index,obj){
			if(obj.checked && (obj.value==1)){
				applyValidate($j('#publishTime').get(0),"date,required");
			}	
		});	
	}
	if(!validateContent($j("#contentForm")[0])){
    	flag = false;
	}
	if($('publishTime')){
		removeValidate($j('#publishTime').get(0));
	}	
	return flag;
}
//保存文章
function saveContent(){
	if(!validateAction()){
    	return ;
    }
    var postData="";
    postData += $j('#contentForm :input').serialize();
    var url=$j('#contentForm').attr('action')+"?doAction=save";
    $j.post(url,postData,saveContentCallback,"json");
}
//保存文章回调函数
function saveContentCallback(data){
	sysMsg(__FMT.contentForm_saveContent_success);
	if(data.contentId){
		$j("#contentId").val(data.contentId);
	}
	if(data.contentTitle){
		$j("#titleSpan").html(__FMT.contentForm_edit + ":"+data.contentTitle);
	}
	displayButtons(data.status);
	displayStatusAndTimeInfo(data);
	refreshParent();
}
//显示时间信息
function displayStatusAndTimeInfo(data){
	if(data.statusMessage){
		$j("#contentStatusSpan").html('&nbsp;&nbsp;&nbsp;&nbsp;'+__FMT.contentForm_currentStatus+':'+'<img src="'+__ctxPath+'/images/icon/contentstatus/contentStatus'+data.status+'.png"/>');
		$j("#contentStatusSpan").show();
	}
	if(data.publishTimeShow){
		$j("#publishTimeSpan").html(data.publishTimeShow);
	}
	if(data.expiredTimeShow){
		$j("#expiredTimeSpan").show();
		$j("#expiredTimeShow").html(data.expiredTimeShow);
	}
	if(data.createTimeShow){
		$j("#createTimeSpan").show();
		$j("#createTimeShow").html(data.createTimeShow);
	}
	if(data.updateTimeShow){
		$j("#updateTimeSpan").show();
		$j("#updateTimeShow").html(data.updateTimeShow);
	}
	
	//displayButtons(data.status);
}

//更新有效期
function updateExpiredContent(){
	var postData = {"contentId":$j("#contentId").val()};
	var url=$j('#contentForm').attr('action')+"?doAction=updateExpired";
    $j.post(url,postData,updateExpiredContentCallback,"json");
}
//更新有效期callback
function updateExpiredContentCallback(data){
	sysMsg(__FMT.contentForm_updateExpired_success);
	displayStatusAndTimeInfo(data);
	displayButtons(data.status);
	refreshParent();
}
// 删除当前编辑的产品
function deleteContent(){
	var entityName = $j("#contentTitle").val();
	if (confirm(__FMT.common_message_confirmDeleteThis + " " + entityName + "?")) {
		var paraData = {
			contentId: $j("#contentId").val()
		};
		$j.post(__ctxPath + "/content/content/blank.html?doAction=delete", paraData, deleteContentCallback,"json");
	}
}
//删除后的回调函数
function deleteContentCallback(data){
	sysMsg("'"+data.contentName+"'"+__FMT.content_delete_success);
	refreshParent();
	returnToList();
}

//从contentForm返回到list
function returnToList(){
	$j('#formDiv').hide();
	$j('#mainDiv').show();
}


//刷新父窗口的产品列表
function refreshParent(){
	refreshContentList();
}


//选择目录
function selectCategory(){
	showDialogOfcontentCategorySelector();
}

//选择目录callback category 是一个json对象 {id，name}
function selectCategoryCallback(category){
	$j.getJSON(__ctxPath+"/content/content/blank.html?doAction=getFullCategoryPathName&categoryId="+category.id,null,getFullCategoryPathNameCallback);
	$j('#categoryId').val(category.id);
	closeDialogOfcontentCategorySelector();
	$j('#categoryId').next('img').remove();//如果有验证错误的移除

}
//根据名称获取目录全名
function getFullCategoryPathNameCallback(data){
	$j('#categoryName').html(data.fullCategoryPathName);
}



//增加图片  media是一个JSON对象{mediaId,mediaDescription,mediaUrl},needMoveIcons用于是否执行函数showImageMoveIcons，用于页面速度优化，默认需要
function addNewContentImage(media,needMoveIcons){
	var id,mediaUrl,src_s0,src_m0,desc;
	//stat : set id,src
	
	id = "_"+media.mediaId;
	mediaUrl = media.mediaUrl;
	src_s0 = __mediaPath + mediaUrl.substring(0,mediaUrl.lastIndexOf("."))+"_s0"+mediaUrl.substring(mediaUrl.lastIndexOf("."));
	src_m0 = __mediaPath + mediaUrl.substring(0,mediaUrl.lastIndexOf("."))+"_m0"+mediaUrl.substring(mediaUrl.lastIndexOf("."));
	desc = media.mediaDescription;
	//end:
	
	var html = '';
	html += '<td class="contentImageDiv" id="image'+id+'">';
	html += '<div  class="img clearfix"><a href="javascript:void(0)" onclick="showBigPict(\'mediaImage'+id+'\')">';
	html += '<img id="mediaImage'+id+'"  src="' + src_s0+ '" src_m0="'+src_m0+'" mediaUrl="'+__mediaPath+mediaUrl+'" width="50" height="50" onerror="this.src=__defaultImage;this.onerror=\'\'" /></a>';
	html += '<div class="do">';
	html += '<a href="javascript:void(0)" name="move_l" class="move_l" onclick="moveUpContentImage(this)">up</a>';
	html += '<a href="javascript:void(0)" name="del" class="del" onclick="removeContentImage(this)">delete</a>';
	html += '<a href="javascript:void(0)" name="move_r" class="move_r" onclick="moveDownContentImage(this)">down</a>';
	html += '</div></div>';
	
	//start: hidden
	html += '<input type="hidden" name="mediaUrls" value="'+media.mediaUrl+'" id="mediaUrl'+id+'"  />';
	html += '<input type="hidden" name="mediaIds" id="mediaId'+id+'" value="mediaId'+id+'"/>';
	html += '<input type="hidden" name="mediaTypes" value="0"/>';
	html += '<input type="hidden" name="mediaDescs" value=""/>';
	//end : hidden
	html += '</td>';
	
	$j('#imageList').append(html);
	$j('#image'+id).bind('mouseover',function(){$j(this).find('.do').show();}).bind('mouseout',function(){$j(this).find('.do').hide();});
	$j('#allPicsDiv').show();
	if(needMoveIcons == null || needMoveIcons){
		showImageMoveIcons();
	}	
	
	//如果是上传的第一幅图,则显示在主图区域
	if($j('#imageList td').length==1){
		showBigPict('mediaImage'+id);
	}
	
}

//在主图区域显示图片
function showBigPict(mediaImageId){
	$j('#contentMainImageDiv').get(0).src = $j('#'+mediaImageId).attr("src_m0");
	$j("#contentMainImageDiv").parent('a').attr("href",$j('#'+mediaImageId).attr("mediaUrl")).attr("target","_blank");
	currentMiddleImageId = $j('#'+mediaImageId).parents(".contentImageDiv").attr("id");

}

//上传文章图片后的回调函数
function uploadContentImagehandler(mediaUrl,fileInputId){
	mediaId++;
	addNewContentImage({"mediaId":'new_'+mediaId,"mediaDescription":"","mediaUrl":mediaUrl});
}

//刷新图片区左移和右移图标是否显示
function showImageMoveIcons(){
	$j('#imageList td.contentImageDiv a[name="move_l"]').addClass("move_l").removeClass("move_l_gray");
	$j('#imageList td.contentImageDiv a[name="move_r"]').addClass("move_r").removeClass("move_r_gray");
	$j('#imageList td.contentImageDiv:first a[name="move_l"]').addClass("move_l_gray").removeClass("move_l");
	$j('#imageList td.contentImageDiv:last a[name="move_r"]').addClass("move_r_gray").removeClass("move_r");
	
}
//删除图片 
//linkDOM 是一个超链接对象
function removeContentImage(linkDOM){
	if (confirm(__FMT.common_message_confirmDeleteThis +"?")) {
		var jContentImage = $j(linkDOM).parents(".contentImageDiv");
		if(jContentImage.attr("id") == currentMiddleImageId){
			//如果删除的小图是当前中图所放大的
			var jContentImageNextDisplay =  jContentImage.next();
			if(jContentImageNextDisplay.length==0){
				jContentImageNextDisplay = jContentImage.prev();
			}
			if(jContentImageNextDisplay.length==0){
				//如果已经没有任何图片
					$j('#contentMainImageDiv').get(0).src = __defaultImage_m0;
					$j("#contentMainImageDiv").parent('a').attr("href","javascript:void(0)").attr("target","");
			}else{
				//删除的图片之后或之前还有图片
				showBigPict(jContentImageNextDisplay.find('img[src_m0]').attr("id"));
			}
		}
		jContentImage.remove();
		
		showImageMoveIcons();
	}
}

//提升图片顺序
//linkDOM 是一个超链接对象
function moveUpContentImage(linkDOM){
	var me = $j(linkDOM).parents(".contentImageDiv");
	var prev = me.prev(".contentImageDiv");
	prev.before(me);
	showImageMoveIcons();
}
//降低图片顺序
//linkDOM 是一个超链接对象
function moveDownContentImage(linkDOM){
	var me = $j(linkDOM).parents(".contentImageDiv");
	var next = me.next(".contentImageDiv");
	next.after(me);
	showImageMoveIcons();
}



//显示自动评估文章
function showAutoEvalContents(linkDOM,typeId){
	if($j("#contentId").val() == ""){
		//case:文章未保存 则显示为“请先保存”
		$j('#autoEvalContentsDiv_'+typeId).empty().append(__FMT.contentDetail_recommendResult_saveFirst);
	}else if($j('#autoEvalArea_'+typeId).html().indexOf("hasShow") == -1){
		//case:第一次展开
		$j('#autoEvalArea_'+typeId).append('<span class="hasShow"/>'); //增加一个显示标志
		var postData = {"contentId":$j("#contentId").val(),"relatedTypeId":typeId};
		var url=$j('#contentForm').attr('action')+"?doAction=getAutoEvalContents";
		$j('#autoEvalContentsDiv_'+typeId).empty().loading();
	    $j.post(url,postData,showAutoEvalContentsCallback,"json");
	}else{
		//case:非第一次展开
	}   
	$j('#autoEvalCloseBtn_'+typeId).show();
	$j('#autoEvalShowBtn_'+typeId).hide();
	$j('#autoEvalArea_'+typeId).slideDown();
	$j(linkDOM).parents(".top:first").addClass("curr");
	
}

//重新评估
function reAutoEvalContents(typeId){
	var postData = {"contentId":$j("#contentId").val(),"relatedTypeId":typeId};
	var url=$j('#contentForm').attr('action')+"?doAction=getAutoEvalContents";
	$j('#autoEvalContentsDiv_'+typeId).empty().loading();
    $j.post(url,postData,showAutoEvalContentsCallback,"json");
}


//显示自动评估文章callback
function showAutoEvalContentsCallback(data){
	var typeId = data.relatedTypeId;
	var contents = data.autoEvalContentArray;
	$j('#autoEvalContentsDiv_'+typeId).empty();
	if(contents.length > 0){
		for(var i=0; i< contents.length; i++){
			addAutoEvalContent("autoEvalContentsDiv_"+typeId,contents[i],typeId);
		}
	}else{
		$j('#autoEvalContentsDiv_'+typeId).append(__FMT.contentDetail_recommendResult_none);
	}	
	$j('#autoEvalCloseBtn_'+typeId).show();
	$j('#autoEvalShowBtn_'+typeId).hide();
	

}
//关闭自动评估显示
function closeAutoEvalContents(linkDOM,typeId){
	$j('#autoEvalCloseBtn_'+typeId).hide();
	$j('#autoEvalShowBtn_'+typeId).show();
	$j('#autoEvalArea_'+typeId).slideUp();
	$j(linkDOM).parents(".top:first").removeClass("curr");
}



//添加自动评估文章
//divId 添加到的区域id； content 是一个json对象{content.id,content.contentTilte,content.imageUrl}; typeId推荐类型id
function addAutoEvalContent(divId,content,typeId){
	var html = '<li>';
	html += '<span class="img"><img src="'+__mediaPath+content.imageUrl+'" width="115" height="115" onerror="this.src=__defaultImage;this.onerror=\'\'" /></img></span>';
	html += '<h4>'+content.contentTitle+'</h4>';
	html += '</li>';
	$j('#'+divId).append(html);
	
}

//手动添加文章
// content 是一个json对象{content.id,content.contentTilte,content.imageUrl}; typeId推荐类型id
function addManulContent(content,typeId){
	relatedContentCounter++;
	var mediaUrl = content.imageUrl;
	var src_s1 = __mediaPath + mediaUrl.substring(0,mediaUrl.lastIndexOf("."))+"_s1"+mediaUrl.substring(mediaUrl.lastIndexOf("."));
	var html = '<td class="relatedContent'+typeId+'"><div class="img clearfix" id="relatedContent'+relatedContentCounter+'">';
	html += '<a href="'+__mediaPath+content.imageUrl+'" target="_blank"><img src="'+src_s1+'" width="100" height="100" onerror="this.src=__defaultImage_s1;this.onerror=\'\'" /></img></a>';
	html += '<h4>'+content.contentTitle+'</h4>';
	html += '<div class="do">';
	html += '<a href="javascript:void(0)" onclick="moveUpRelatedContent(this,'+typeId+')" name="move_l" class="move_l"></a>';
	html += '<a href="javascript:void(0)" onclick="removeRelatedContent(this,'+typeId+')" class="del"></a>';
	html += '<a href="javascript:void(0)" onclick="moveDownRelatedContent(this,'+typeId+')" name="move_r" class="move_r"></a>';
	html += '</div>';
	//start:hidden
	html += '<input type="hidden" name="relatedContentIds" value="'+content.id+'"/>';
	html += '<input type="hidden" name="relatedTypeIds" value="'+typeId+'"/>';
	//end:hidden
	html += '</div></td>';
	$j('#manualContentsDiv_'+typeId).append(html);
	$j('#relatedContent'+relatedContentCounter).bind('mouseover',function(){$j(this).find('.do').show();$j(this).addClass("curr");}).bind('mouseout',function(){$j(this).find('.do').hide();$j(this).removeClass("curr");});
	showRelatedContentMoveIcons(typeId);
}


//删除
//linkDOM 是一个超链接对象
function removeRelatedContent(linkDOM,typeId){
	if (confirm(__FMT.common_message_confirmDeleteThis +"?")) {
		$j(linkDOM).parents(".relatedContent"+typeId).remove();
		showRelatedContentMoveIcons(typeId);
	}	
}


//提升推荐顺序
//linkDOM 是一个超链接对象
function moveUpRelatedContent(linkDOM,typeId){
	var me = $j(linkDOM).parents(".relatedContent"+typeId);
	var prev = me.prev(".relatedContent"+typeId);
	prev.before(me);
	showRelatedContentMoveIcons(typeId);
}

//降低推荐顺序
//linkDOM 是一个超链接对象
function moveDownRelatedContent(linkDOM,typeId){
	var me = $j(linkDOM).parents(".relatedContent"+typeId);
	var next = me.next(".relatedContent"+typeId);
	next.after(me);
	showRelatedContentMoveIcons(typeId);
}

//刷新图片区左移和右移图标是否显示
function showRelatedContentMoveIcons(typeId){
	$j('#manualContentsDiv_'+typeId+' td.relatedContent'+typeId+' a[name="move_l"]').addClass("move_l").removeClass("move_l_gray");
	$j('#manualContentsDiv_'+typeId+' td.relatedContent'+typeId+' a[name="move_r"]').addClass("move_r").removeClass("move_r_gray");
	$j('#manualContentsDiv_'+typeId+' td.relatedContent'+typeId+':first a[name="move_l"]').addClass("move_l_gray").removeClass("move_l");
	$j('#manualContentsDiv_'+typeId+' td.relatedContent'+typeId+':last a[name="move_r"]').addClass("move_r_gray").removeClass("move_r");
}


//通过文章选择器选择推荐文章
function selectRelatedContent(typeId){
	currentTypeId = typeId;
	showDialogOfcontentSelector();
}
//通过文章选择器选择推荐文章callback
function selectRelatedContentCallback(contentArray){
	var typeId = currentTypeId;
	closeDialogOfcontentSelector();
	for(var i=0; i< contentArray.length; i++)
	{
		var content = contentArray[i];
		if($j('#manualContentsDiv_'+typeId).find('input[name="relatedContentIds"][value="'+content.contentId+'"]').length!=0){
			//不能添加重复元素
			jAlert(content.contentTitle+__FMT.contentForm_adddRecommended_noRepeat);
		}else if($j('#contentId').val() == content.contentId){
			//不能添加自身
			jAlert(content.contentTitle+__FMT.contentForm_adddRecommended_noSelf);
		}else{	
			//无重复和自我
			addManulContent({"id":content.contentId,"contentTitle":content.contentTitle,"imageUrl":content.imageUrl},typeId);
		}	
	}
		
}
//清空所有关联文章
function removeAllRelatedContent(typeId){
	if (confirm(__FMT.common_message_confirmClear +"?")) {
		$j('#manualContentsDiv_'+typeId).empty();
	}	
}

